package cn.tedu.tmall.basic.service.impl;

import cn.tedu.tmall.basic.dao.persist.repository.IDistrictRepository;
import cn.tedu.tmall.basic.dao.repository.IDistrictCacheRepository;
import cn.tedu.tmall.basic.pojo.po.DistrictPO;
import cn.tedu.tmall.basic.service.IDistrictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 处理省市区数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 3.0
 */
@Slf4j
@Service("DistrictServiceInitByParentImpl")
public class DistrictServiceInitByParentImpl implements IDistrictService {

    @Autowired
    private IDistrictRepository districtRepository;

    @Autowired
    private IDistrictCacheRepository districtCacheRepository;

    public DistrictServiceInitByParentImpl() {
        log.debug("创建业务类对象：DistrictServiceImpl");
    }

    @Override
    public List<DistrictPO> listByParent(Long parentId) {
        log.debug("开始执行【根据父级查询子级地区列表】的业务，参数：{}", parentId);
        //return districtRepository.listByParent(parentId);
        return districtCacheRepository.listByParent(parentId);
    }

    /**
     * 优点 占用内存相对少
     * 缺点 多次查询数据库
     */
    @Override
    public void initDict() {
        //1先查所有的parentId 并且去重
        List<Long> all = districtRepository.listAllParentIds();
        if (CollectionUtils.isEmpty(all)){
            log.error("查询省市区信息为空");
            //报警... 通知dba,op,通知领导.(待商榷)
        }else {
            //删除redis
            districtCacheRepository.deleteAll();
            all.forEach(parentId->{
                //循环去重的parentIds,通过parentId查询当前parentId下的省市区
                List<DistrictPO> districtPOS =
                        districtRepository.listByParent(parentId);
                //保存到redis
                districtCacheRepository.saveDict(parentId,districtPOS);
            });
        }
    }
}
